How to do addition or subtraction on CSS Variables

116

:root {
  --margin: 50px;
  --margin--: calc(var(--margin) * -1));
 /* 
 while you may simply write like below
 but I love to use as above 
 coz, we'll only need to change value 
 in one place if needed
 */
 /* --margin--: -50px; */
}

.positive-margin {
  margin: var(--margin);
}
.negative-margin {
  margin-left: var(--margin--);
}
:root {
  --margin: 50px;
}

body {
  margin: 0 100px;
  border:1px solid;
}

.box-1 {
  background: red;
  height: 100px;
  width: 200px;
  margin-left: calc(-1 * var(--margin));
}

.box-2 {
  background: green;
  height: 100px;
  width: 200px;
  margin-left: calc(-1 * (-1 * var(--margin))); /* You can also nest calculation */
}

Comments

Submit
0 Comments